package com.sunnay.interceptor;

import com.sunnay.annotation.Login;
import com.sunnay.enums.GbCodeEnum;
import com.sunnay.constant.GbRedisKey;
import com.sunnay.exception.DataException;
import com.sunnay.util.RedisUtil;
import com.sunnay.vo.auth.SystemUser;
import com.sunnay.web.ContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthInterceptor implements HandlerInterceptor {

    RedisUtil redisUtil;

    public AuthInterceptor(RedisUtil redisUtil){
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Login loginRequired= handlerMethod.getMethodAnnotation(Login.class);
            if (loginRequired==null || loginRequired.require()) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    //查询是否在踢人名单中
                    if (redisUtil.containKeyByHash(GbRedisKey.GB_ONLINE_KICK_KEY, session.getId())) {
                        ContextHelper.clearSystemUser(session);
                        redisUtil.delHashObject(GbRedisKey.GB_ONLINE_KICK_KEY,session.getId());
                        throw new DataException(GbCodeEnum.USER_SINGLE_LOGIN);
                    }
                    SystemUser systemUser = ContextHelper.getSystemUser();
                    if (systemUser.getId() == null) {
                        throw new DataException(GbCodeEnum.USER_NOT_LOGIN);
                    }
                    if (StringUtils.isNotBlank(systemUser.getOnlineKey())) {
                        String sessionId = (String) redisUtil.getHashObject(String.format(GbRedisKey.GB_ONLINE_KEY,session.getId()), systemUser.getOnlineKey());
                        if (StringUtils.isBlank(sessionId)|| !sessionId.equals(session.getId())) {
                            ContextHelper.clearSystemUser(session);
                            throw new DataException(GbCodeEnum.USER_NOT_LOGIN);
                        }
                    }
                }else{
                    throw new DataException(GbCodeEnum.USER_NOT_LOGIN);
                }
            }
        }

        return true;
    }
}
